local ByteArray = require("framework.cc.utils.ByteArray");
local SocketTCP = require("framework.cc.net.init").SocketTCP;
local Packet = require(SCRIPTS_DIR .. ".network.Packet")
local TcpNet = class("TcpNet")
function TcpNet:ctor()
    -- body
    self.socket = nil;
end

function TcpNet:init()
    -- body
    mgrs.log:printDebug("socket time:" .. SocketTCP.getTime());
    mgrs.log:printDebug("os time:" .. os.time());
    local socket = SocketTCP.new();
    socket:setName("GameTcp");
    --socket:setTickTime(1);
    --socket:setReconnTime(6);
    socket:setConnFailTime(4);
    socket:addEventListener(SocketTCP.EVENT_DATA, handler(self,self.tcpReceive));
    socket:addEventListener(SocketTCP.EVENT_CLOSE, handler(self,self.tcpClose));
    socket:addEventListener(SocketTCP.EVENT_CLOSED, handler(self,self.tcpClosed));
    socket:addEventListener(SocketTCP.EVENT_CONNECTED, handler(self,self.tcpConnected));
    socket:addEventListener(SocketTCP.EVENT_CONNECT_FAILURE, handler(self,self.tcpError));
    mgrs.log:printDebug("version is " .. SocketTCP._VERSION);
    self.socket = socket;
    SocketTCP._DEBUG = true;
end

function TcpNet:connectSocket(host, port)
    -- body
    self:init();
    self.socket:connect(host, port, false);
end

function TcpNet:tcpClose(event)
    -- body
    mgrs.proto:socketExit(self);
end

function TcpNet:tcpClosed(event)
    -- body
    mgrs.proto:socketClosed(self);
end

function TcpNet:tcpConnected(event)
    -- body
    mgrs.proto:socketSucess(self);
end

function TcpNet:tcpError(event)
    -- body
    mgrs.proto:socketError(self);
end

--tcp直接shutdown();
function TcpNet:closeSocket()
    -- body
    self:close();
    self.socket:disconnect();--会接收到SocketTCP.EVENT_CLOSED事件触发scnet.tcpClosed()
end

--关闭定时器
function TcpNet:close()
    -- body
    if self.socket.isConnected then
        self.socket:close();--会接收到SocketTCP.EVENT_CLOSE事件触发scnet.tcpClose()
    end
end

-- 接收数据
function TcpNet:tcpReceive(event)
    -- body
    mgrs.proto:parseMessage(event.data)
end

-- 发送数据 msgid 消息id,data 消息数据
function TcpNet:sendData(data)
    -- body
    self.socket:send(data);
end



return TcpNet;

--endregion
